# Tiny dictionary
dictionary = %w(pangolin ecstatic oligarchy corridor)

# our max number of bas guesses 
MAX = 6

# Pick a word at random
word = dictionary[rand(dictionary.size)-1].upcase
guesses = 0

# Replace all characters by underscores.
current = word.gsub(/./, "_")
while guesses < MAX
  # print the word with letters found.  Separate characters with a space.
  puts current.gsub(/([A-Z_])/, "\\1 ")
  print "Enter a letter (#{guesses}/#{MAX})> "
  input = gets.chomp.upcase
  
  # check that the input is one letter
  if input.size > 1 or not (input =~ /[[:alpha:]]/)
    puts "Please enter a valid character (1 letter)..."
    next
  end

  # if the letter is in the word
  if word.index(input) != nil
    for i in 0...word.size
      # if current character is the input, replace the '_'
      if word[i].chr == input
        current[i] = input
      end
    end
    # if all letters are replaced, we've found the word, hurray!
    if current == word
      puts "Well done! The word was #{word}"
    exit
    end
  else 
    # if the letter is not in the word, increase guesses number.
    guesses += 1    
  end
end

# If here, we haven't found on time...
puts "You lost! The word was #{word}"